package gg.zsw.datasource.demo.kafka;

import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.common.TopicPartition;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.listener.ConsumerSeekAware;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

/**
 * @author zhou.sw
 * @Date 2020/6/30 16:08
 */
@Slf4j
@Component
@Configuration
@DependsOn("messageTopic")
public class KafkaMessageListener implements ConsumerSeekAware {

    /**
     * messageTopic的泛型类型未定，使用者自己搞定。
     */
    @Autowired
    private MessageTopic messageTopic;

    @KafkaListener(topics = "${kafka.consumer.topics}", containerFactory = "kafkaListenerContainerFactory")
    public void onBatchMessages(List<ConsumerRecord<String, String>> consumerRecordList) {
        log.debug("receive message, size:" + consumerRecordList.size());
        for (ConsumerRecord<String, String> consumerRecord : consumerRecordList) {
            if (messageTopic != null) {
                messageTopic.handle(consumerRecord);
            } else {

            }
        }
    }

    @Override
    public void registerSeekCallback(ConsumerSeekCallback callback) {

    }

    /**
     * 再均衡监听器
     * onPartitionsAssigned方法会在重新分配分区之后和消费者开始读取消息之前被调用
     *
     * @param assignments
     * @param callback
     */
    @Override
    public void onPartitionsAssigned(Map<TopicPartition, Long> assignments, ConsumerSeekCallback callback) {
        // 从最新开始消费，忽略之前未消费的
        for (TopicPartition topicPartition : assignments.keySet()) {
            callback.seekToEnd(topicPartition.topic(), topicPartition.partition());
        }
    }

    @Override
    public void onIdleContainer(Map<TopicPartition, Long> assignments, ConsumerSeekCallback callback) {

    }

}
